﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using GmailMetroNotifier.Client.Common;
using GmailMetroNotifier.Client.Properties;
using GmailMetroNotifier.Client.UI;
using GmailMetroNotifier.Client.UIP;

namespace GmailMetroNotifier.Client
{
    internal static class Program
    {
        private static readonly NotificationManager _notificationManager = new NotificationManager(new DesktopNotificationProvider(), null, null);
        
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        internal static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += new WeakEventHandler<object, UnhandledExceptionEventArgs>(AppDomain_UnhandledException).Handler;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string[] arguments = Environment.GetCommandLineArgs();

            if (arguments.Length > 3)
            {
                _notificationManager.Desktop.Notify(Resources.DESKTOP_INCORRECT_SYNTAX_MESSAGE, NotificationSeverity.Error);
            }
            else if (arguments.Length > 1 && string.Equals(arguments[1], "-register", StringComparison.CurrentCultureIgnoreCase))
            {
                string shortcutName = arguments[2];

                bool shortcutCreated = ShellHelper.TryCreateShortcut(shortcutName, Constants.ApplicationId);

                if (shortcutCreated)
                {
                    _notificationManager.Desktop.Notify(Resources.DESKTOP_MSG_SHORTCUT_CREATED.FormatWith(CultureInfo.CurrentCulture, shortcutName), NotificationSeverity.Information);
                }
                else
                {
                    _notificationManager.Desktop.Notify(Resources.DESKTOP_MSG_SHORTCUT_NOT_CREATED, NotificationSeverity.Warning);
                }
            }
            else
            {
                Application.Run(new MainForm());
            }
        }

        private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Logger.LogError(Resources.LOG_MSG_UNHANDLED_EXCEPTION, e.ExceptionObject);

            _notificationManager.Desktop.Notify(Resources.DESKTOP_MSG_UNHANDLED_EXCEPTION, NotificationSeverity.Error);

            // Exit in a ordered manner
            Application.Exit();
        }
    }
}
